package com.jz.community.basecomm.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.util.Util;
import com.jz.community.basecomm.glideConfig.GetBitmapImageListener;
import com.jz.community.basecomm.glideConfig.GlideCircleTransform;
import com.jz.community.basecomm.glideConfig.GlideRoundTransform;
import com.jz.community.basecommunity.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Tony.Fan on 2018/3/13 15:22
 * <p>
 * imageLoader的默认的加载图片设置
 */
public class BaseImageLoaderUtils {

    private static final String TAG = "ImageLoaderUtils";
    private static BaseImageLoaderUtils utils = null;

    protected BaseImageLoaderUtils() {
    }

    public static BaseImageLoaderUtils getInstance() {
        if (utils == null) {
            utils = new BaseImageLoaderUtils();

        }
        return utils;
    }

    /**
     * 圆角
     */
    public class RoundShape {
        public int radio;

        public RoundShape(int radio) {
            this.radio = radio;
        }
    }

    /**
     * 默认的加载图片方式 ,这里面的默认 加载图片的颜色为灰色
     *
     * @param image
     * @param url
     */
    public void loadDefaltImage(Context context, ImageView image, String url) {
        loadImage(context, false, image, url);
    }

    /**
     * 自定义加载图
     *
     * @param image
     * @param url
     */
    public void loadSpecifyBgImage(Context context, ImageView image, String url, int loadingImgBg) {
        loadImage(context, image, url, loadingImgBg, null);
    }

    /**
     * 加载背景随机颜色的图片
     *
     * @param image
     * @param url
     */
    public void loadRamdomImage(Context context, ImageView image, String url) {
        loadImage(context, true, image, url);
    }

    /**
     * 加载背景随机颜色的圆角图片
     *
     * @param image
     * @param url
     * @param round 圆角度数 单位px
     */
    public void loadRamdomRoundImage(Context context, ImageView image, String url, int round) {
        int loadBgImageId = getLoadingBgColor(true);
        loadRoundImage(context, image, url, loadBgImageId, round);
    }

    /**
     * @param context
     * @param isRadom
     * @param image
     * @param url
     */
    private void loadImage(Context context, boolean isRadom, ImageView image, String url) {
        int loadBgImageId = getLoadingBgColor(isRadom);
        loadImage(context, image, url, loadBgImageId, null);
    }

    /**
     * glide 加载图片
     *
     * @param context
     * @param image
     * @param url
     * @param defaultColorId
     * @param roundShape
     */
    private void loadImage(Context context, ImageView image, String url, int defaultColorId, RoundShape roundShape) {
        setNormalGlideOptions(context, image, url, defaultColorId, roundShape);
    }


    /**
     * 获取Bitmap
     *
     * @param context
     * @param url
     * @param getBitmapImageListener
     */
    public void loadImageBitmap(Context context, String url, GetBitmapImageListener getBitmapImageListener,int round) {
        if (Preconditions.isNullOrEmpty(url)){
            return;
        }
        RequestOptions myOptions = new RequestOptions()
                .transform(new GlideRoundTransform(context, round))
                .placeholder(getLoadingBgColor(false))
                .error(getLoadingBgColor(false));

        Glide.with(context)
                .asBitmap()
                .apply(myOptions)
                .load(url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        if (getBitmapImageListener != null) {
                            getBitmapImageListener.success(resource);
                        }
                    }
                });
    }
    /**
     * 获取Bitmap
     *
     * @param context
     * @param url
     * @param getBitmapImageListener
     */
    public void loadImageBitmap(Context context, String url, GetBitmapImageListener getBitmapImageListener) {
        if (Preconditions.isNullOrEmpty(url)){
            return;
        }
        RequestOptions myOptions = new RequestOptions()
                .placeholder(getLoadingBgColor(false))
                .error(getLoadingBgColor(false));


        Glide.with(context)
                .asBitmap()
                .apply(myOptions)
                .load(url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        if (getBitmapImageListener != null) {
                            if (isOnMainThread(context)) {
                                getBitmapImageListener.success(resource);
                            }
                        }
                    }
                });
    }

    /**
     * glide 加载圆角图片
     *
     * @param context
     * @param image
     * @param url
     * @param defaultColorId
     */
    private void loadRoundImage(Context context, ImageView image, String url, int defaultColorId, int round) {
        LoggerUtils.fLog().d(TAG + url);
        if (isOnMainThread(context)) {
            RequestOptions myOptions = new RequestOptions()
                    .transform(new GlideRoundTransform(context, round))
                    .placeholder(defaultColorId) //设置占位图，在加载之前显示
                    .error(defaultColorId); //在图像加载失败时显示
            glidIntoImage(context, image, url, myOptions);
        }
    }

    public void loadRoundImage(Context context, ImageView image, String url, int defaultImgId, Transformation<Bitmap> transformation) {
        if (isOnMainThread(context)) {
            RequestOptions myOptions = new RequestOptions()
                    .transform(transformation)
                    .placeholder(defaultImgId) //设置占位图，在加载之前显示
                    .error(defaultImgId); //在图像加载失败时显示
            glidIntoImage(context, image, url, myOptions);
        }
    }

    public void loadImage(Context context, ImageView image, String url, int defaultImgId) {
        if (isOnMainThread(context)) {
            RequestOptions myOptions = new RequestOptions()
                    .placeholder(defaultImgId) //设置占位图，在加载之前显示
                    .error(defaultImgId); //在图像加载失败时显示
            glidIntoImage(context, image, url, myOptions);
        }
    }

    public void loadImage(Context context, ImageView image, int url, int defaultImgId) {
        if (isOnMainThread(context)) {
            RequestOptions myOptions = new RequestOptions()
                    .placeholder(defaultImgId) //设置占位图，在加载之前显示
                    .error(defaultImgId); //在图像加载失败时显示
            glidIntoImage(context, image, url, myOptions);
        }
    }

    /**
     * glide 加载圆形图片
     *
     * @param context
     * @param image
     * @param url
     * @param defaultColorId
     */
    private void loadCircleImage(Context context, ImageView image, String url, int defaultColorId) {
        LoggerUtils.fLog().d(TAG + url);
        RequestOptions myOptions = new RequestOptions()
                .transform(new GlideCircleTransform(context))
                .placeholder(defaultColorId) //设置占位图，在加载之前显示
                .error(defaultColorId); //在图像加载失败时显示
        glidIntoImage(context, image, url, myOptions);
    }

    /**
     * Glide 通用设置
     *
     * @param mContext
     * @param image
     * @param url
     * @param defaultColorId
     * @param roundShape
     */
    protected void setNormalGlideOptions(Context mContext, ImageView image, String url, int defaultColorId, RoundShape roundShape) {
        RequestOptions myOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
               // .placeholder(defaultColorId) //设置占位图，在加载之前显示
                .error(defaultColorId); //在图像加载失败时显示

        glidIntoImage(mContext, image, url, myOptions);
    }

    private void glidIntoImage(Context mContext, ImageView image, String url, RequestOptions myOptions) {
        if (Preconditions.isNullOrEmpty(url)) {
            return;
        }
        if (url.endsWith("gif")) {
            Glide.with(mContext)
                    .asGif()
                    .load(url)
                    .apply(myOptions)
                    .into(image);
        } else {
            Glide.with(mContext)
                    .asBitmap()
                    .load(url)
                    .apply(myOptions)
                    .into(image);
        }

    }

    private void glidIntoImage(Context mContext, ImageView image, int url, RequestOptions myOptions) {
        if (Preconditions.isNullOrEmpty(url)) {
            return;
        }
        Glide.with(mContext)
                .load(url)
                .apply(myOptions)
                .into(image);
    }

    /**
     * 加载本地gif图片
     *
     * @param mContext
     * @param image
     * @param source
     */
    public void loadGifImage(Context mContext, ImageView image, int source) {
        Glide.with(mContext)
                .asGif()
                .load(source)
                .into(image);
    }

    /**
     * 在滑动停止的时候，resumeRequests()恢复请求
     *
     * @param mContext
     */
    public void resumeRequests(Context mContext) {
        if (isOnMainThread(mContext)) {
            Glide.with(mContext).resumeRequests();
        }
    }

    /**
     * 在滑动的时候，调用pauseRequests()取消请求
     *
     * @param mContext
     */
    public void pauseRequests(Context mContext) {
        if (isOnMainThread(mContext)) {
            Glide.with(mContext).pauseRequests();
        }
    }

    private boolean isOnMainThread(Context context) {
        if (context == null){
            return false;
        }
        if (context instanceof Activity) {
            try {
                //如果finish直接返回false
                if (((Activity) context).isFinishing()) {
                    return false;
                }
            } catch (Exception exp) {
                return false;
            }
        }
        return Util.isOnMainThread();

    }

    /**
     * 生成随机颜色
     *
     * @param isRadom
     * @return
     */
    private List<Integer> mRecentShowNum = new ArrayList<>();//最近显示的颜色下标
    public static final int NOT_REPEAT_NUM = 3;  //表示不重复颜色数

    public int getLoadingBgColor(boolean isRadom) {
        if (isRadom) {
            int[] colorArr = {R.color.xiu_radom_color_1, R.color.xiu_radom_color_2, R.color.xiu_radom_color_3,
                    R.color.xiu_radom_color_4, R.color.xiu_radom_color_5, R.color.xiu_radom_color_6};

            if (colorArr != null && colorArr.length > 0) {

                int radomIdx;

                while (true) {
                    radomIdx = new Random().nextInt(colorArr.length - 1);
                    if (!mRecentShowNum.contains(radomIdx)) {
                        break;
                    }
                }
                mRecentShowNum.add(0, radomIdx);

                if (mRecentShowNum.size() > NOT_REPEAT_NUM) {
                    //表示三个相联颜色不重复
                    mRecentShowNum.remove(mRecentShowNum.size() - 1);
                }
                return colorArr[radomIdx];
            }
        }
        return R.color.xiu_page_bg;
    }
}
